<template>
    <div class="w-full">
        <div class="flex gap-3 bg-white p-3 rounded-lg">
            <el-form :inline="true" :model="searchForm" class="w-full">
                <el-form-item label="姓名：" class="mb-0">
                  <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="电话：" class="mb-0">
                  <el-input v-model="searchForm.phone" placeholder="请输入电话" clearable />
                </el-form-item>
                <el-form-item label="呼叫方向：" class="mb-0 w-1/6">
                  <el-select
                    v-model="searchForm.callDirection"
                    placeholder="请选择呼叫方向"
                    class="w-full"
                    clearable
                  >
                    <el-option label="呼入" value="呼入" />
                    <el-option label="呼出" value="呼出" />
                  </el-select>
                </el-form-item>
                <el-form-item label="通话时间：" class="mb-0">
                    <el-date-picker
                        v-model="searchForm.date"
                        type="daterange"
                        range-separator="To"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                    />
                </el-form-item>
                <el-form-item class="mb-0">
                  <el-button type="primary" @click="search" class="w-1/6">搜索</el-button>
                  <el-button type="default" @click="resetSearchForm" class="w-1/6">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="bg-white p-3 rounded-lg mt-3">
            <el-table :data="tableData" border>
                <el-table-column prop="index" label="序号" min-width="40" />
                <el-table-column prop="name" label="姓名" min-width="100" />
                <el-table-column prop="phone" label="电话" min-width="100" />
                <el-table-column prop="callDirection" label="呼叫方向" min-width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.callDirection === '呼入' ? 'success' : 'danger'">{{ scope.row.callDirection }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="isConnected" label="是否接通" min-width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.isConnected === '是' ? 'success' : 'info'">{{ scope.row.isConnected }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="callTime" label="拨打时间" min-width="100" />
                <el-table-column prop="callDuration" label="通话时长" min-width="100" />
                <el-table-column label="操作" min-width="80">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleCallRecord(scope.row)">通话录音</el-button>                    
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end">
                <el-pagination background layout="prev, pager, next" :total="total" class="mt-4"/>
            </div>
        </div>        
        <!-- 通话录音弹窗 -->
        <Drawer
            v-model="dialogVisible"
            title="通话录音"
            width="600px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :isShowConfirm="false"
        >
            <div class="p-4">
                <!-- 录音信息 -->
                <div class="mb-4">
                    <div class="flex items-center gap-4 text-sm text-gray-600">
                        <div>开始时间：{{ currentRecord.callTime }}</div>
                        <div>主叫号码：{{ currentRecord.phone }}</div>
                    </div>
                </div>

                <!-- 播放控制按钮组 -->
                <div class="flex items-center gap-2 mb-4">
                    <el-radio-group v-model="playSpeed" size="small">
                        <el-radio-button label="normal">正常</el-radio-button>
                        <el-radio-button label="1.5">1.5倍速</el-radio-button>
                        <el-radio-button label="2">2倍速</el-radio-button>
                    </el-radio-group>
                </div>

                <!-- 波形图 -->
                <div class="w-full h-32 bg-black rounded-lg mb-4">
                    <!-- 这里可以集成音频波形可视化组件 -->
                    <div class="wave-form">
                        <!-- 波形图将在这里显示 -->
                    </div>
                </div>

                <!-- 音频播放控制器 -->
                <div class="flex items-center gap-4">
                    <el-button 
                        :icon="isPlaying ? VideoPause : VideoPlay"
                        @click="togglePlay"
                        size="small"
                        :disabled="!currentRecord.audioUrl"
                    >
                        {{ isPlaying ? '暂停' : '播放' }}
                    </el-button>
                    <div class="flex-1">
                        <el-slider 
                            v-model="currentTime" 
                            :max="duration"
                            :format-tooltip="formatTime"
                            @change="handleTimeChange"
                            :disabled="!currentRecord.audioUrl"
                        />
                    </div>
                    <audio 
                        ref="audioPlayer"
                        :src="currentRecord.audioUrl"
                        @timeupdate="handleTimeUpdate"
                        @loadedmetadata="handleMetadata"
                        @ended="handleEnded"
                        @error="handleAudioError"
                        preload="auto"
                    ></audio>
                    <span class="text-sm text-gray-600">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
                    <el-button 
                        @click="toggleMute"
                        size="small"
                        :disabled="!currentRecord.audioUrl"
                    ></el-button>
                </div>
            </div>
        </Drawer>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { getCallRecords } from '@/api/ConsultingServiceApi';
import { ElMessage } from 'element-plus';
import Drawer from '@/components/common/Drawer.vue';
const tableData = ref([
    {
        index: 1,
        name: '张三',
        phone: '13800138000',
        callDirection: '呼入',
        isConnected: '是',
        callTime: '2024-07-22 09:25:55',
        callDuration: '10秒'
    },
    {
        index: 2,
        name: '李四',
        phone: '13800138001',
        callDirection: '呼出',
        isConnected: '否',
        callTime: '2024-07-22 09:25:55',
        callDuration: '10秒'
    }
])
const searchForm = ref({
    name: '',
    phone: '',
    callDirection: ''
})
const total = ref(tableData.value.length)
const pageSize = ref(10)
const currentPage = ref(1)

// 通话录音相关
const dialogVisible = ref(false)
const currentRecord = ref({})
const audioPlayer = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const playSpeed = ref('normal')

// 添加音频加载状态
const isLoading = ref(false)
const hasError = ref(false)

// 获取数据的方法
const getCallRecordsData = () => {
    // 实现获取数据的逻辑
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value
    }
    if (searchForm.value.name) {
        params.name = searchForm.value.name
    }
    if (searchForm.value.phone) {
        params.phone = searchForm.value.phone
    }
    if (searchForm.value.callDirection) {
        params.callDirection = searchForm.value.callDirection
    }
    if (searchForm.value.date) {
        params.date = searchForm.value.date
    }
    getCallRecords(params).then(res => {
        console.log(res)
    })
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
    pageSize.value = val
    // 这里可以调用获取数据的方法
    getCallRecordsData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    // 这里可以调用获取数据的方法
    getCallRecordsData()
}

// 搜索
const search = () => {
    console.log('搜索', searchForm.value)
    getCallRecordsData()
}

// 重置搜索条件
const resetSearchForm = () => {
    searchForm.value = {
        name: '',
        phone: '',
        callDirection: ''
    }
}

// 处理通话录音
const handleCallRecord = async (row) => {
    currentRecord.value = row
    dialogVisible.value = true
    isLoading.value = true
    hasError.value = false
    
    try {
        // 这里应该是从后端获取音频URL的API调用
        // const response = await getAudioUrl(row.id)
        // currentRecord.value.audioUrl = response.data.url
        
        // 临时使用测试音频
        currentRecord.value.audioUrl = 'https://www2.cs.uic.edu/~i101/SoundFiles/StarWars60.wav'
        
        // 重置播放状态
        isPlaying.value = false
        currentTime.value = 0
        duration.value = 0
        
    } catch (error) {
        console.error('获取音频文件失败:', error)
        ElMessage.error('获取音频文件失败，请稍后重试')
        hasError.value = true
    } finally {
        isLoading.value = false
    }
}

// 音频错误处理
const handleAudioError = (error) => {
    console.error('音频加载失败:', error)
    ElMessage.error('音频文件加载失败，请稍后重试')
    hasError.value = true
    isLoading.value = false
}

// 播放/暂停切换
const togglePlay = () => {
    if (!audioPlayer.value) return
    
    if (isPlaying.value) {
        audioPlayer.value.pause()
    } else {
        audioPlayer.value.play()
    }
    isPlaying.value = !isPlaying.value
}

// 静音切换
const toggleMute = () => {
    if (!audioPlayer.value) return
    audioPlayer.value.muted = !audioPlayer.value.muted
}

// 时间格式化
const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 处理音频元数据加载
const handleMetadata = () => {
    if (!audioPlayer.value) return
    duration.value = audioPlayer.value.duration
}

// 处理时间更新
const handleTimeUpdate = () => {
    if (!audioPlayer.value) return
    currentTime.value = audioPlayer.value.currentTime
}

// 处理播放结束
const handleEnded = () => {
    isPlaying.value = false
    currentTime.value = 0
}

// 处理时间改变
const handleTimeChange = (value) => {
    if (!audioPlayer.value) return
    audioPlayer.value.currentTime = value
}

// 监听播放速度变化
watch(playSpeed, (newSpeed) => {
    if (!audioPlayer.value) return
    switch (newSpeed) {
        case 'normal':
            audioPlayer.value.playbackRate = 1
            break
        case '1.5':
            audioPlayer.value.playbackRate = 1.5
            break
        case '2':
            audioPlayer.value.playbackRate = 2
            break
    }
})

// 监听对话框关闭
watch(dialogVisible, (newVal) => {
    if (!newVal) {
        // 清理音频播放状态
        if (audioPlayer.value) {
            audioPlayer.value.pause()
            audioPlayer.value.currentTime = 0
        }
        isPlaying.value = false
        currentTime.value = 0
        duration.value = 0
        hasError.value = false
    }
})

// 组件卸载时清理
onUnmounted(() => {
    if (audioPlayer.value) {
        audioPlayer.value.pause()
        audioPlayer.value = null
    }
})
</script>

<style scoped>
.wave-form {
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom, #1e3c72, #2a5298);
    position: relative;
}

.wave-form::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 2px;
    background: rgba(255, 255, 255, 0.2);
}

:deep(.el-slider__runway) {
    margin: 0;
}

:deep(.el-dialog__body) {
    padding: 0;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
}
</style>
